package cn.steam.service;

import cn.steam.dao.RoleDao;
import cn.steam.dao.UserDao;
import cn.steam.dao.UserRoleDao;
import cn.steam.entity.Role;
import cn.steam.entity.User;
import cn.steam.entity.UserInfo;
import cn.steam.entity.UserRole;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhang jintao on 2022/05/02
 **/
@Service
public class UserService implements UserDetailsService {

    @Autowired
    UserDao userDao;
    @Autowired
    RoleDao roleDao;
    @Autowired
    UserRoleDao userRoleDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userDao.findOne(Example.of(User.builder()
                .userName(username).build())).orElse(null);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user, userInfo);
        List<UserRole> userRoles = userRoleDao.findAll(Example.of(UserRole.builder().
                userId(user.getUserId()).build()));
        if (CollectionUtils.isEmpty(userRoles)) {
            return userInfo;
        }
        List<String> roleCodes = userRoles.stream().map(UserRole::getRoleCode).collect(Collectors.toList());
        List<Role> roles = roleDao.findAllByRoleCodeIn(roleCodes);
        userInfo.setRoles(roles);
        return userInfo;
    }


}
